<template>
  <div class="app-container">
    <div class="filter-container">

      <el-input v-model="listQuery.userName" placeholder="姓名" style="width: 260px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.userAge" placeholder="年龄" style="width: 260px;" class="filter-item"
        @keyup.enter.native="handleFilter" />

        <el-select v-model="listQuery.userName" placeholder="性别" style="width: 260px;" class="filter-item"
        @keyup.enter.native="handleFilter">
        <el-option label="男" value="男"></el-option>
        <el-option label="女" value="女"></el-option></el-select>

        <el-input v-model="listQuery.idCardNumber" placeholder="身份证号" style="width: 260px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.userPhone" placeholder="手机号" style="width: 260px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
        <el-select v-model="listQuery.isOwner" placeholder="是否业主" style="width: 260px;" class="filter-item"
        @keyup.enter.native="handleFilter">
        <el-option label="是" value="1"></el-option>
        <el-option label="否" value="0"></el-option></el-select>
        <el-input v-model="listQuery.roomNumber" placeholder="门牌号" style="width: 260px;" class="filter-item"
        @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('table.export') }}
      </el-button>
    </div>
   <!--表格内容-->
   <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="userId" 
      sortable="custom" align="center" width="80" :class-name="getSortClass('userId')">
        <template slot-scope="{row}">
          <span>{{ row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="userName" 
      sortable="custom" align="center" width="120" >
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="userAge" 
      sortable="custom" align="center" width="120" >
        <template slot-scope="{row}">
          <span>{{ row.userAge }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="userSex" 
      sortable="custom" align="center" width="120" >
        <template slot-scope="{row}">
          <span>{{ row.userSex }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" prop="idCardNumber" 
      sortable="custom" align="center" width="180" >
        <template slot-scope="{row}">
          <span>{{ row.idCardNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="userPhone" 
      sortable="custom" align="center" width="180" >
        <template slot-scope="{row}">
          <span>{{ row.userPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否业主" prop="isOwner" 
      sortable="custom" align="center" width="180" >
        <template slot-scope="{row}">
          <span>{{ row.isOwner==0?'否':'是'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="门牌号" prop="roomNumber" 
      sortable="custom" align="center" width="180" >
        <template slot-scope="{row}">
          <span>{{ row.roomNumber }}</span>
        </template>
      </el-table-column>
      <!--表格内部按钮-->
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
     <!--修改的表单-->
     <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 400px; margin-left:50px;">
        <el-form-item label="居民ID">
          <el-input v-model="temp.userId" :autosize="{ minRows: 2, maxRows: 4}" 
           retype="text" readonly=""/>
        </el-form-item>
        <el-form-item label="姓名" :rules="[ { required: true, message: '姓名不能为空', trigger: 'blur' } ]">
          <el-input v-model="temp.userName" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="Please input" />
        </el-form-item>
        <el-form-item label="年龄" :rules="[ { required: true, message: '年龄不能为空', trigger: 'blur' } ]">
          <el-input v-model="temp.userAge" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="Please input" />
        </el-form-item>
        <el-form-item label="性别" :rules="[ { required: true, message: '性别不能为空', trigger: 'blur' } ]">
          <el-select v-model="temp.userSex" placeholder="Please select" filterable>
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" :rules="[ { required: true, message: '身份证号不能为空', trigger: 'blur' } ]">
          <el-input v-model="temp.idCardNumber" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="Please input" />
        </el-form-item>
        <el-form-item label="手机号" :rules="[ { required: true, message: '手机号不能为空', trigger: 'blur' } ]">
          <el-input v-model="temp.userPhone" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="Please input" />
        </el-form-item>
        <el-form-item label="是否业主" :rules="[ { required: true, message: '是否业主', trigger: 'blur' } ]">
          <el-select v-model="temp.isOwner" placeholder="Please select" filterable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门牌号" :rules="[ { required: true, message: '门牌号不能为空', trigger: 'blur' } ]"> 
          <el-select v-model="temp.roomId" placeholder="请选择" 
          clearable class="filter-item" style="width: 220px">
            <el-option v-for=" item in roomList" :key="item.roomId" :label="'门牌号：'+item.roomNumber" :value="item.roomId" />
          </el-select>
        </el-form-item> 
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {addUser,deleteUser,updateUser,findByPage} from '@/api/user'
import {findRoomList} from '@/api/room'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        userId:undefined,
        userName:undefined,
        userSex:undefined,
        userAge:undefined,
        idCardNumber:undefined,
        userPhone:undefined,
        isOwner:undefined,
        facePhoto:undefined,
        roomId:undefined,
        password:undefined,
        roomNumber:undefined
      },
      showReviewer: false,
      temp: {
        userId:undefined,
        userName:undefined,
        userSex:undefined,
        userAge:undefined,
        idCardNumber:undefined,
        userPhone:undefined,
        isOwner:undefined,
        facePhoto:undefined,
        roomId:undefined,
        password:undefined,
        roomNumber:undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        userName: [{ required: true, message: '居民姓名不能为空', trigger: 'change' }],
        idCardNumber: [{ required: true, message: '身份证不能为空', trigger: 'change' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'change' }],
        roomNumber: [{ required: true, message: '门牌号不能为空', trigger: 'change' }]
      },
      downloadLoading: false,
      roomList:[]
    }
  },
  created() {
    this.getList()
    this.getRoomList()
  },
  methods: {
    getRoomList(){
      //设置未加载
      this.listLoading = true;
        //Axios请求后端 
        findRoomList().then(response => {
          //给集合赋值
          this.roomList = response.data.list
          //赋值查询总条数
              setTimeout(() => {
                this.listLoading = false//设置为已经加载成功
              }, 1.5 * 1000)
            
         })
    },
   /**
     * 筛选查询
     */
     getList() {//获取 list  total
      //设置未加载
        this.listLoading = true;
        //Axios请求后端 
        findByPage(this.listQuery).then(response => {
          //给集合赋值
          this.list = response.data.list
          //赋值查询总条数
          this.total = response.data.total
          //
              setTimeout(() => {
                this.listLoading = false//设置为已经加载成功
              }, 1.5 * 1000)
            
         })
        
    },
    /**
     * 点击搜索按钮触发的时间
     */
    handleFilter() {
      //默认第一页
      this.listQuery.page = 1
      this.getList()//调用搜索
    },
    //排序
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    //重置数据
    resetTemp() {
      this.temp = {
        userId:undefined,
        userName:undefined,
        userSex:undefined,
        userAge:undefined,
        idCardNumber:undefined,
        userPhone:undefined,
        isOwner:undefined,
        facePhoto:undefined,
        roomId:undefined,
        password:undefined,
        roomNumber:undefined
      }
    },
    //点击添加按钮调用的时间
    handleCreate() {
      this.resetTemp()//重置数据
      this.dialogStatus = 'create'//表单状态为 添加
      this.dialogFormVisible = true//打开表单
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //点击添加内的按钮的时间
    createData() {
      //验证表单数据是否符合验证规则
      this.$refs['dataForm'].validate((valid) => {
        //判断验证是否通过
        if (valid) {     
         //Axios请求后端 
        addUser(this.temp).then(response => {
            //把当前内容添加到 集合中
          // this.list.unshift(this.temp)
          this.getList();
           //设置是否被不通过
           this.dialogFormVisible = false//关闭表单
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    //点击表格内部修改按钮调用的时间
    handleUpdate(row) {
      //获取这一行的数据 放到 temp 中
      this.temp = Object.assign({}, row) // copy obj
      //表单状态为 修改
      this.dialogStatus = 'update'
      //打开表单
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //点击表单内部按钮是 修改的触发时间
    updateData() {
      //验证表单数据是否符合验证规则
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          //临时数据   temp内容拷贝到tempData
          const tempData = Object.assign({}, this.temp)
             //Axios请求后端 
          updateUser(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            //替换
           //重新查询表格数据
           this.getList();
            this.dialogFormVisible = false //关闭表单
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      //Axios请求后端 
      deleteUser(row.userId).then(() => {
            this.getList();
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
    },
    //下载
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    //转换json数据格式
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    //获取排序名称
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
